package com.demo.cloud.shiro.realm;

import java.util.HashSet;
import java.util.Set;

import javax.annotation.Resource;

import com.demo.cloud.shiro.bean.User;
import com.demo.cloud.shiro.serivce.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;



public class MyRealm extends AuthorizingRealm {

    @Resource
    private UserService userService;

    /**
     * 认证：身份认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        User user = userService.getUserByUsername(username);
        if (user != null) {
            AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(user.getUserName(), user.getPassword(), getName());
            return authcInfo;
        } else {
            return null;
        }
    }

    /**
     * 授权：权限认证
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        //String userName = (String) principals.getPrimaryPrincipal();
        //authorizationInfo.setRoles(userService.getRoles(userName));
        //authorizationInfo.setStringPermissions(userService.getPermissions(userName));

        Set<String> stringSet = new HashSet<>();
        stringSet.add("user:view");
        stringSet.add("user:edit");
        authorizationInfo.setStringPermissions(stringSet);
        return authorizationInfo;
    }
}